
using Youz.Common.BLL;
using Youz.Common.Entity;
using Youz.Common.Helper;
using Youz.CreditRepay.DAL;
using Youz.CreditRepay.Entity;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using System.Web;

namespace Youz.CreditRepay.BLL
{
    /// <summary>
    /// Member_Info BLL Class
    /// </summary>
    public partial class Member_InfoBLL : BaseBLL
    {
        Member_InfoDAL dal;

        public Member_InfoBLL()
        {
            dal = new Member_InfoDAL();
            base.ModuleName = "Member_Info";
            base.MenuName = "Member_Info";
        }

        #region  成员方法
        /// <summary>
        ///  新增一条数据
        /// </summary>
        public bool Add(Member_Info model)
        {
            var r = dal.Add(model);

            base.WriteOperationLog(OperationType.Add, r, Core.GetJsonByObjectHaveTime(model));

            return r;
        }

        /// <summary>
        ///  保存一条数据
        /// </summary>
        public bool Update(Member_Info model)
        {
            var r = dal.Update(model);
            //  base.WriteOperationLogSensitive(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model), 1, "密码修改");
            base.WriteOperationLog(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model));

            return r;
        }
        public bool UpdateEmail(Member_Info model)
        {
            var r = dal.Update(model);
            base.WriteOperationLogSensitive(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model), 1, "密保邮箱更换");
            //base.WriteOperationLog(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model));

            return r;
        }
        public bool UpdateMobileNo(Member_Info model)
        {
            var r = dal.Update(model);
            base.WriteOperationLogSensitive(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model), 1, "密保手机更换");
            //base.WriteOperationLog(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model));

            return r;
        }
        public bool UpdatePwd(Member_Info model)
        {
            var r = dal.Update(model);
            base.WriteOperationLogSensitive(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model), 1, "密码修改");
            //base.WriteOperationLog(OperationType.Update, r, Core.GetJsonByObjectHaveTime(model));

            return r;
        }
        /// <summary>
        /// 删除一条数据
        ///</summary>
        public bool Delete(String MemberAccount)
        {
            var r = dal.Delete(MemberAccount);

            base.WriteOperationLog(OperationType.Delete, r, MemberAccount);

            return r;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Member_Info Get(String MemberAccount)
        {
            return dal.Get(MemberAccount);
        }

        /// <summary>
        /// 得到一个JSON对象
        /// </summary>
        public string GetJson(String MemberAccount)
        {
            return Core.GetJsonByObject(Get(MemberAccount));
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet Gets(string sqlWhere)
        {
            return dal.Gets(sqlWhere);
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet Gets(int top, string sqlWhere, string filedOrder)
        {
            return dal.Gets(top, sqlWhere, filedOrder);
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string sqlWhere)
        {
            return dal.GetRecordCount(sqlWhere);
        }

        /// <summary>
        /// 获得数据列表分页
        /// </summary>
        public DataTable Gets(string sqlWhere, int pageindex, int pagesize, out int total, params SqlParameter[] cmdParms)
        {
            return dal.Gets(sqlWhere, pageindex, pagesize, out total, cmdParms);
        }
        #endregion  成员方法

        /// <summary>
        /// 激活会员帐号
        /// </summary>
        /// <param name="memberAccount">会员帐号</param>
        public bool AcitvateAccount(string memberAccount)
        {
            var r = dal.AcitvateAccount(memberAccount);

            base.WriteOperationLog(OperationType.Update, r, memberAccount);

            return r;
        }

        /// <summary>
        /// 用户是否被锁定或禁用
        /// </summary>
        /// <param name="memberAccount"></param>
        /// <returns></returns>
        public bool IsLocked(string memberAccount)
        {
            return dal.IsLocked(memberAccount);
        }

        /// <summary>
        /// 锁定用户
        /// </summary>
        /// <param name="memberAccount"></param>
        /// <returns></returns>
        public bool Lock(string memberAccount)
        {
            var r = dal.Lock(memberAccount);

            base.WriteOperationLog(OperationType.Update, r, memberAccount);

            return r;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public string CreateMemberAccount()
        {
            Member_Info model = null;
            string memberAccount = null;
            do
            {
                memberAccount = CommonHelper.GetUNIXTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")) + ValidateCode.GetRandomNum(2);
                model = dal.Get(memberAccount);
            } while (model != null);

            return memberAccount;
        }

        public string Validator(Member_Info model)
        {
            if (string.IsNullOrWhiteSpace(model.LastName))
                return "姓名不能为空";
            if (string.IsNullOrWhiteSpace(model.MobileNo))
                return "手机号不能为空";
            //if (!ValidationHelper.IsMobileNo(model.MobileNo))
            //    return "手机号格式不正确";
            return string.Empty;
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool ExistsMobileNo(string MobileNo)
        {
            return dal.ExistsMobileNo(MobileNo);
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool ExistsEmail(string Email)
        {
            return dal.ExistsEmail(Email);
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool ExistsMobileNo(string MobileNo, string MemberAccount)
        {
            return dal.ExistsMobileNo(MobileNo, MemberAccount);
        }

        public void SendSMS(string memberAccount, string message)
        {
            Member_Info member = Get(memberAccount);

            if (member != null && !string.IsNullOrEmpty(member.MobileNo))
            {
                Task.Run(() => { SMSBLL.SendSMS(member.MobileNo, message); });
            }
        }

        public string GetAuthCode(string MobileNo, string msg)
        {
            if (string.IsNullOrWhiteSpace(MobileNo))
                return Utility.AjaxResult(false, "错误的手机号码");            

            string code = RandHelper.Number(4);
            SessionHelper.Set("phonecode", MobileNo + code);

            ReturnMessage result = SMSBLL.SendCode("86" + MobileNo, code, msg);

            return Utility.AjaxResult(result.Result, result.Message);
        }

        public string GetRegisterAuthCode()
        {
            string MobileNo = WebHelper.Post<String>("MobileNo");
            string type = WebHelper.Post("Type");
            bool ischeck = WebHelper.Post<bool>("IsCheck");

            if (ischeck)
            {
                if (ExistsMobileNo(MobileNo))
                    return Utility.AjaxResult(false, "手机号已注册");
            }
            else
            {
                if (!ExistsMobileNo(MobileNo))
                    return Utility.AjaxResult(false, "手机号未注册");
            }

            return GetAuthCode(MobileNo, type);
        }

        public string GetForgetPasswordAuthCode()
        {
            string MobileNo = WebHelper.Post<String>("MobileNo");

            return GetAuthCode(MobileNo, "忘记密码");
        }

        #region  会员统计
        /// <summary>
        /// 获得各个区域下的人数(不包括未激活的)
        /// </summary>
        public DataTable AreaNum(string sqlWhere, int pageindex, int pagesize, out int total, params SqlParameter[] cmdParms)
        {
            return dal.AreaNum(sqlWhere, pageindex, pagesize, out total, cmdParms);
        }
        /// <summary>
        /// 当前会员总数(不包括未激活的)
        /// </summary>
        /// <returns></returns>
        public int SumCount()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" status!=0 ");
            if (new Member_AreaBLL().CheckIsAgents())//判断是否为管理角色
            {
                sb.AppendFormat(" and MemberAccount in (select MemberAccount from [dbo].[Member_Info] where Referrer in (select AreaName from [dbo].[Member_Area] where AgentsAccount = '{0}'))", Core.MemberAccount);
            }
            return GetRecordCount(sb.ToString());
        }
        /// <summary>
        /// 今天新增会员数
        /// </summary>
        /// <returns></returns>
        public int TodayAddCount(string Area)
        {
            StringBuilder sb = new StringBuilder();
            string StartDate = Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd");
            string EndDate = Convert.ToDateTime(DateTime.Now).AddDays(1).ToString("yyyy-MM-dd");
            sb.AppendFormat(" CreateTime>='{0}' and CreateTime<'{1}' ", StartDate, EndDate);
            if (Area.Trim() != "")
            {
                sb.AppendFormat("  and Area = '{0}'", Area);
            }

            return GetRecordCount(sb.ToString());
        }
        /// <summary>
        /// 活跃量（天/星期/月）
        /// </summary>
        /// <returns></returns>
        public DataSet TodayActiveVolume(string date)
        {

            StringBuilder sb = new StringBuilder();
            //DateTime currentStartWeek;       //本周周一
            //DateTime currentEndWeek;         //本周周日
            //DateTime currentStartMonth;      //本月月初
            //DateTime currentEndMonth;        //本月月末
            DateTime currentDateTime;        //当前时间
            int currentDayOfWeek;            //今天星期几
            currentDateTime = DateTime.Now;
            currentDayOfWeek = Convert.ToInt32(currentDateTime.DayOfWeek.ToString("d"));    //今天星期几
            //string StartDate = Convert.ToDateTime(currentDateTime).ToString("yyyy-MM-dd");
            //string EndDate = Convert.ToDateTime(currentDateTime).AddDays(1).ToString("yyyy-MM-dd");
            string EndDate = Convert.ToDateTime(currentDateTime).AddDays(+1).ToString("yyyy-MM-dd");
            string StartDate = Convert.ToDateTime(currentDateTime).AddDays(-14).ToString("yyyy-MM-dd");
            switch (date)
            {
                case "Day":
                    EndDate = Convert.ToDateTime(currentDateTime).AddDays(+1).ToString("yyyy-MM-dd");
                    StartDate = Convert.ToDateTime(currentDateTime).AddDays(-14).ToString("yyyy-MM-dd");
                    break;
                #region
                //case "Week":
                //    currentStartWeek = currentDateTime.AddDays(1 - ((currentDayOfWeek == 0) ? 7 : currentDayOfWeek));   //本周周一
                //    currentEndWeek = currentStartWeek.AddDays(6);//本周周末
                //    StartDate = currentStartWeek.ToString("yyyy-MM-dd");
                //    EndDate = currentEndWeek.AddDays(1).ToString("yyyy-MM-dd");
                //    break;
                //case "Month":
                //    currentStartMonth = currentDateTime.AddDays(1 - currentDateTime.Day);   //本月月初
                //    currentEndMonth = currentStartMonth.AddMonths(1).AddDays(-1);           //本月月末
                //    StartDate = currentStartMonth.ToString("yyyy-MM-dd");
                //    EndDate = currentEndMonth.AddDays(1).ToString("yyyy-MM-dd");
                //    break;
                //default:
                //    break;
                #endregion
            }
            sb.AppendFormat(" b.LoginType='2' and b.CreateDate>='{0}' and  b.CreateDate<'{1}' ", StartDate, EndDate);
            sb.AppendFormat(" group by CONVERT(varchar(100),b.CreateDate, 112) order by CreateDate ");//a.Area,c.AreaName,

            return dal.TodayActiveVolume(sb.ToString());
        }
        /// <summary>
        /// 交易活跃量（天）
        /// </summary>
        /// <returns></returns>
        public DataSet TodayTradeActiveVolume()
        {

            StringBuilder sb = new StringBuilder();

            DateTime currentDateTime;        //当前时间
            int currentDayOfWeek;            //今天星期几
            currentDateTime = DateTime.Now;
            currentDayOfWeek = Convert.ToInt32(currentDateTime.DayOfWeek.ToString("d"));    //今天星期几
            string EndDate = Convert.ToDateTime(currentDateTime).AddDays(+1).ToString("yyyy-MM-dd");
            string StartDate = Convert.ToDateTime(currentDateTime).AddDays(-14).ToString("yyyy-MM-dd");
            sb.AppendFormat("  b.CreateTime>='{0}' and  b.CreateTime<'{1}' and ChangeType  in(300,302) ", StartDate, EndDate);
            sb.AppendFormat(" group by CONVERT(varchar(100),b.CreateTime, 112) order by CreateTime desc ");

            return dal.TodayTradeActiveVolume(sb.ToString());
        }
        #endregion

        /// <summary>
        /// 会员盈亏分页
        /// </summary>
        public DataTable MemberProfitPager(string sqlWhere, int pageindex, int pagesize, out int total)
        {
            return dal.MemberProfitPager(sqlWhere, pageindex, pagesize, out total);
        }

        /// <summary>
        /// 更新APP客户端ID
        /// </summary>
        /// <param name="memberAccount"></param>
        /// <param name="appID"></param>
        public void UpdateAppID(string memberAccount, string appID)
        {
            dal.UpdateAppID(memberAccount, appID);
        }

        public void LogoutApp(string memberAccount)
        {
            dal.LogoutApp(memberAccount);
        }

        public void SetNickname(string memberAccount, string nickname)
        {
            dal.SetNickname(memberAccount, nickname);
        }

        public void ChangeLoginPassword(string memberAccount, string password)
        {
            dal.ChangeLoginPassword(memberAccount, password);
        }

        public void ChangePayPassword(string memberAccount, string password)
        {
            dal.ChangePayPassword(memberAccount, password);
        }

        public string GetMemberAcountByReferrerCode(Int64 ReferrerCode)
        {
            return dal.GetMemberAcountByReferrerCode(ReferrerCode);
        }

        public string GetAppUserData(string memberAccount, Member_Info member)
        {
            if (string.IsNullOrEmpty(memberAccount))
            {
                return Core.AjaxResult(false, "参数错误");
            }
            if (member == null)
            {
                member = new Member_InfoBLL().Get(memberAccount);
            }

            var mc = new Member_CertifiedBLL().Get(memberAccount);
            var asset = new Member_AccountBLL().Get(memberAccount);

            return Core.AjaxResult(true, "Succeed", new
            {
                Settings = new
                {
                    Recharge = new
                    {
                        RechargeMinAmount = BLL.ConfigParameters.Recharge.RechargeMinAmount,
                        RechargeFee = BLL.ConfigParameters.Recharge.RechargeFee
                    },
                    GetCash = new
                    {
                        GetCashMinAmount = BLL.ConfigParameters.GetCash.GetCashMinAmount,
                        GetCashMaxAmount = BLL.ConfigParameters.GetCash.GetCashMaxAmount,
                        GetCashFee = BLL.ConfigParameters.GetCash.GetCashFee,
                    },
                    Repayment = new
                    {
                        MaxBillAmount = BLL.ConfigParameters.Repayment.MaxBillAmount,
                        CashDepositRate = BLL.ConfigParameters.Repayment.CashDepositRate,
                        MinCashDeposit = BLL.ConfigParameters.Repayment.MinCashDeposit
                    },
                },
                Banks = new Sys_BankBLL().Gets(),
                User = new
                {
                    Nickname = member.Nickname,
                    MemberAccount = member.MemberAccount,
                    MobileNo = member.MobileNo,
                    Email = member.Email,
                    AuthenticationStatus = (int)(mc == null ? AuditStatus.Unknown : mc.Status),
                    Realname = mc == null ? string.Empty : mc.Name,
                    ReferrerCode = member.ReferrerCode,
                    IDNo = mc == null ? string.Empty : mc.CredentialsNum,
                    UnreadMessage = new CMS_MessageBLL().GetUnreadCount(member.MemberAccount)
                },
                Asset = asset
            });
        }
        
        public string Login(string userName, string appID, Member_Info model)
        {
            string _LoginID = Core.WriteLoginLog(true, userName, (int)Core.CurrentSiteType, "登录成功");
            string userData = string.Format("{0},{1} {2},{3},{4}", _LoginID, model.FirstName, model.LastName, model.Email, model.MobileNo);
            //创建票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddDays(30), false, userData);
            //加密票据
            string authTicket = FormsAuthentication.Encrypt(ticket);
            //存储为cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket);
            cookie.Expires = ticket.Expiration;
            HttpContext.Current.Response.Cookies.Add(cookie);

            if (!string.IsNullOrEmpty(appID) && appID != model.AppID)
            {
                if (!string.IsNullOrEmpty(model.AppID))
                {
                    var payloadResult = AppPusher.PushToSingle(model.AppID, (int)AppPusherType.KickoutMember);

                    Core.WriteOperationLog("API", "PayPush", string.Format("{0} - {1} - {2}", userName, appID, payloadResult));
                }

                UpdateAppID(userName, appID);
            }

            return GetAppUserData(userName, model);
        }

        public string Register()
        {
            string mobile = WebHelper.Post<String>("Mobile");
            string authCode = WebHelper.Post<String>("AuthCode");
            string password = WebHelper.Post<String>("Password");
            string appID = WebHelper.Post<String>("AppID");
            var ReferrerCode = WebHelper.Post<Int64>("ReferrerCode");
            string referrer = string.Empty;

            if (string.IsNullOrEmpty(mobile))
            {
                return Utility.AjaxResult(false, "请输入手机号");
            }
            if (string.IsNullOrEmpty(password))
            {
                return Utility.AjaxResult(false, "请输入登录密码");
            }
            if (string.IsNullOrEmpty(authCode))
            {
                return Utility.AjaxResult(false, "请输入验证码");
            }
            if (ExistsMobileNo(mobile))
            {
                return Utility.AjaxResult(false, "该手机号已经注册");
            }

            if (ReferrerCode > 0)
            {
                referrer = GetMemberAcountByReferrerCode(ReferrerCode);
                if (string.IsNullOrEmpty(referrer))
                {
                    return Utility.AjaxResult(false, "邀请码不存在");
                }
            }

            string phonecode = SessionHelper.Get("phonecode") as string;
            //if ((mobile + authCode) != phonecode)
            //    return Utility.AjaxResult(false, "验证码不正确或已过期");

            Member_Info model = new Member_Info();
            model.MemberAccount = mobile;// CreateMemberAccount();
            model.MobileNo = mobile;
            model.LoginPwd = CommonHelper.GetSHA512(password);
            model.Referrer = referrer;
            model.ReferrerCode = GenerateReferrerCode();
            model.CreateTime = DateTime.Now;
            model.Status = MemberStatus.Normal;            
            
            Member_Account account = new Member_Account()
            {
                MemberAccount = model.MemberAccount,
                CreateTime = model.CreateTime,
                ModifyTime = model.CreateTime
            };

            if (Add(model) && new Member_AccountBLL().Add(account))
            {
                return Login(mobile, appID, model);
            }
            else
            {
                return Utility.AjaxResult(false, AjaxResultType.Save);
            }
        }

        public string SetNewPassword()
        {
            string mobileNo = WebHelper.Post<String>("Mobile");
            string password = WebHelper.Post<String>("Password");
            string authCode = WebHelper.Post<String>("AuthCode");

            if (string.IsNullOrWhiteSpace(mobileNo))
                return Utility.AjaxResult(false, "手机号不能为空");
            if (string.IsNullOrWhiteSpace(authCode))
                return Utility.AjaxResult(false, "验证码不能为空");
            if (string.IsNullOrWhiteSpace(password))
                return Utility.AjaxResult(false, "密码不能为空");

            //string phonecode = SessionHelper.Get("phonecode") as string;
            //if ((mobileNo + authCode) != phonecode)
            //    return Utility.AjaxResult(false, "验证码不正确或已过期");

            Member_Info model = Get(mobileNo);
            if (model == null)
                return Utility.AjaxResult(false, "帐号不存在");
            if (model.MobileNo != mobileNo)
                return Utility.AjaxResult(false, "手机号错误");

            model.LoginPwd = CommonHelper.GetSHA512(password);

            return Update(model) ? Utility.AjaxResult(true) : Utility.AjaxResult(false, "设置新密码失败");
        }

        public Int64 GenerateReferrerCode()
        {
            return dal.GenerateReferrerCode();
        }
    }
}


